#include "Delegate.h"
#include <QtMath>
#include <QRandomGenerator>
#pragma execution_character_set("utf-8")

// ============== BigDataModel 实现 ==============

/**
 * @brief BigDataModel构造函数
 * @param rows 行数
 * @param cols 列数
 * @param parent 父对象
 */
BigDataModel::BigDataModel(int rows, int cols, QObject *parent)
    : QStandardItemModel(rows, cols, parent)
{
    // 设置表头标签
    setHorizontalHeaderLabels({"ID", "名称", "进度", "评分", "状态"});

    // 初始化数据缓存
    m_rowDataCache.resize(rows);

    // 创建并连接定时器
    m_updateTimer = new QTimer(this);
    connect(m_updateTimer, &QTimer::timeout, this, &BigDataModel::updateRandomData);
    m_updateTimer->start(1000); // 每1000毫秒更新一次
}

/**
 * @brief 获取指定索引的数据
 * @param index 数据索引
 * @param role 数据角色
 * @return 数据值
 */
QVariant BigDataModel::data(const QModelIndex &index, int role) const
{
    if (!index.isValid()) return QVariant();

    int row = index.row();
    int col = index.column();

    // 首次访问时标记为未加载
    if (!m_loadedRows.contains(row)) {
        m_loadedRows.insert(row, false);
    }

    if (role == Qt::DisplayRole || role == Qt::EditRole) {
        if (row >= m_visibleStart && row <= m_visibleEnd) {
            // 延迟加载机制：如果行数据未加载，则加载
            if (!m_loadedRows[row]) {
                loadRowData(row);
            }

            // 返回真实数据
            switch(col) {
            case 0: return QVariant(row);          // ID
            case 1: return QVariant(QString("项目 %1").arg(row)); // 名称
            case 2: return QVariant(qrand() % 100); // 进度
            case 3: return QVariant(qrand() % 6);   // 评分 (0-5)
            case 4: return QVariant(row % 3 ? "正常" : "警告"); // 状态
            }
        }
        // 未加载区域显示特殊标记
        return QVariant("◌");
    }
    return QStandardItemModel::data(index, role);
}

/**
 * @brief 加载指定行的数据
 * @param row 行号
 */
void BigDataModel::loadRowData(int row) const
{
    // 检查行号是否有效
    if (row < 0 || row >= m_rowDataCache.size()) return;

    // 如果已加载，则直接返回
    if (m_loadedRows.value(row, false)) return;

    // 设置初始值
    m_rowDataCache[row].resize(columnCount());
    m_rowDataCache[row][0] = row;                          // ID
    m_rowDataCache[row][1] = QString("项目 %1").arg(row);  // 名称
    m_rowDataCache[row][2] = QRandomGenerator::global()->bounded(100); // 进度（0-99）%
    m_rowDataCache[row][3] = QRandomGenerator::global()->bounded(6);   // 评分 (0-5)
    m_rowDataCache[row][4] = row % 3 ? "正常" : "警告";    // 状态

    // 标记为已加载
    m_loadedRows[row] = true;
}

/**
 * @brief 设置可见范围
 * @param start 起始行
 * @param end 结束行
 */
void BigDataModel::setVisibleRange(int start, int end)
{
    m_visibleStart = qMax(0, start);
    m_visibleEnd = qMin(rowCount() - 1, end);

    // 通知视图显示区域变化
    emit dataChanged(index(m_visibleStart, 0),
                     index(m_visibleEnd, columnCount() - 1));
}

/**
 * @brief 设置动态更新
 * @param enable 是否启用
 */
void BigDataModel::setDynamicUpdates(bool enable)
{
    m_dynamicEnabled = enable;
    if (enable && !m_updateTimer->isActive()) {
        m_updateTimer->start(1000);
    } else if (!enable && m_updateTimer->isActive()) {
        m_updateTimer->stop();
    }
}

/**
 * @brief 更新随机数据
 */
void BigDataModel::updateRandomData()
{
    if (!m_dynamicEnabled) return;

    // 更新当前可见区域的数据
    for (int row = m_visibleStart; row <= m_visibleEnd; ++row) {
        if (!m_loadedRows.value(row, false)) {
            loadRowData(row);
        } else {
            // 随机更新值
            if (QRandomGenerator::global()->bounded(10) > 5) {  // 50%概率更新进度
                m_rowDataCache[row][2] = (m_rowDataCache[row][2].toInt() + QRandomGenerator::global()->bounded(-5, 6));
                if (m_rowDataCache[row][2].toInt() > 100) m_rowDataCache[row][2] = 100;
                if (m_rowDataCache[row][2].toInt() < 0) m_rowDataCache[row][2] = 0;
            }

            if (QRandomGenerator::global()->bounded(10) > 7) {  // 30%概率更新评分
                m_rowDataCache[row][3] = QRandomGenerator::global()->bounded(6);
            }

            if (QRandomGenerator::global()->bounded(10) > 8) {  // 20%概率更新状态
                m_rowDataCache[row][4] = row % 3 ? "正常" : "警告";
            }
        }
    }

    // 通知视图刷新
    emit dataChanged(index(m_visibleStart, 0), index(m_visibleEnd, columnCount() - 1));
}

// ============== ProgressBarDelegate 实现 ==============

/**
 * @brief 绘制进度条
 * @param painter 绘图工具
 * @param option 选项
 * @param index 索引
 */
void ProgressBarDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option,
                                const QModelIndex &index) const
{
    // 只处理第三列（进度列）
    if (index.column() != 2) {
        QStyledItemDelegate::paint(painter, option, index);
        return;
    }

    int progress = index.data().toInt();

    // 保存当前绘图状态
    painter->save();
    // 设置抗锯齿
    painter->setRenderHint(QPainter::Antialiasing, true);
    // 不绘制边框
    painter->setPen(Qt::NoPen);

    // 绘制背景
    QRect bgRect = option.rect.adjusted(1, 1, -1, -1);
    painter->setBrush(QColor(240, 240, 240));
    painter->drawRoundedRect(bgRect, 4, 4);

    // 绘制进度条
    QRect progressRect = bgRect.adjusted(1, 1, -1, -1);
    progressRect.setWidth(progressRect.width() * progress / 100);

    // 创建渐变效果
    QLinearGradient gradient(progressRect.topLeft(), progressRect.topRight());
    gradient.setColorAt(0, QColor(89, 214, 253));   // #59D6FD
    gradient.setColorAt(1, QColor(11, 139, 255));   // #0B8BFF

    painter->setBrush(gradient);
    painter->drawRoundedRect(progressRect, 3, 3);

    // 绘制文本
    QString text = QString::number(progress) + "%";
    painter->setPen(QColor(51, 51, 51)); // #333
    painter->drawText(bgRect, Qt::AlignCenter, text);

    // 恢复绘图状态
    painter->restore();
}

// ============== StarRatingDelegate 实现 ==============

/**
 * @brief 绘制星级评分
 * @param painter 绘图工具
 * @param option 选项
 * @param index 索引
 */
void StarRatingDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option,
                               const QModelIndex &index) const
{
    // 只处理第四列（评分列）
    if (index.column() != 3) {
        QStyledItemDelegate::paint(painter, option, index);
        return;
    }

    int stars = index.data().toInt();
    painter->save();
    painter->setRenderHint(QPainter::Antialiasing, true);

    // 计算星星位置
    const int starCount = 5;
    qreal starSize = option.rect.height() * 0.6;
    qreal spacing = starSize * 0.3;
    qreal totalWidth = (starSize + spacing) * starCount - spacing;
    QPointF startPoint(option.rect.x() + (option.rect.width() - totalWidth) / 2,
                       option.rect.center().y());

    // 绘制每个星星
    for (int i = 0; i < starCount; ++i) {
        QPointF center = startPoint + QPointF(i * (starSize + spacing), 0);

        // 创建五角星路径
        QPolygonF starPolygon;
        for (int k = 0; k < 5; ++k) {
            // 外顶点 (72度间隔)
            qreal outAngle = qDegreesToRadians(1.0 * -90 + k * 72);
            starPolygon << center + QPointF((starSize/2) * cos(outAngle),
                                            (starSize/2) * sin(outAngle));

            // 内顶点 (36度偏移)
            qreal inAngle = qDegreesToRadians(1.0 * -90 + 36 + k * 72);
            starPolygon << center + QPointF((starSize/4) * cos(inAngle),
                                            (starSize/4) * sin(inAngle));
        }

        // 绘制星星
        if (i < stars) {
            painter->setBrush(QColor(255, 215, 0));  // 金色 #FFD700
            painter->setPen(QPen(QColor(255, 165, 0), 1)); // 橙色描边 #FFA500
            painter->drawPolygon(starPolygon);
        } else {
            painter->setBrush(Qt::NoBrush);  // 空心填充
            painter->setPen(QPen(QColor(200, 200, 200), 1)); // 灰色边框
            painter->drawPolygon(starPolygon);
        }
    }

    painter->restore();
}
